using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace ClientTools.Server.Webservices
{
    public class ClientToolsBaseService: System.Web.Services.WebService
    {
        /// <summary>
        /// Authenticates the specified user.
        /// </summary>
        /// <param name="UserName">Name of the user.</param>
        /// <param name="Password">The password.</param>
        /// <param name="Service">The type of service.</param>
        /// <returns></returns>
        protected umbraco.BusinessLogic.User Authenticate(string userName, string password, ServiceTypeEnum service)
        {
            string configFilePath = System.Web.HttpContext.Current.Server.MapPath("/config/ClientTools.config");
            if (!System.IO.File.Exists(configFilePath))
            {
                throw new Exceptions.ConfigurationNotFoundException();
            }

            // first check if Username and Password is given...
            if (userName == null || userName.Trim() == "" || password == null || password.Trim() == "")
            {
                throw new Exceptions.NotAllCredentialsGivenException();
            }

            // first step of authentication is to verify the user against the umbraco user
            umbraco.BusinessLogic.User umbracoUser;
            try
            {
                umbracoUser = new umbraco.BusinessLogic.User(userName);
            }
            catch (Exception)
            {
                throw new Exceptions.UserNotFoundException();
            }
            if (umbracoUser.Password != password)
            {
                throw new Exceptions.IncorrectCredentialsException();
            }

            // now check if the user is configured
            // First get the ConfigObject: Read all the settings from ClientTools.config
            ConfigClasses.ClientTools config;
            try
            {
                System.Xml.Serialization.XmlSerializer ser
                    = new System.Xml.Serialization.XmlSerializer(typeof(ConfigClasses.ClientTools));
                using (System.IO.FileStream fs = new System.IO.FileStream(configFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    config = (ConfigClasses.ClientTools)ser.Deserialize(fs);
                }
            }
            catch (Exception)
            {
                throw new Exceptions.IncorrectConfigurationFileException();
            }

            // Check if the config is enabled
            if (config.Enabled == false)
            {
                throw new Exceptions.ConfigurationDisbaledException();
            }

            // Get the related user from the ConfigObject
            ConfigClasses.User user = config.GetUserByName(userName);
            if (user == null)
            {
                throw new Exceptions.UserNotConfiguredException();
            }

            // Check if the user is enabled
            if (user.Enabled == false)
            {
                throw new Exceptions.UserDisabledException();
            }

            // Dependend on which service is selected...
            switch (service)
            {
                case ServiceTypeEnum.MaintenanceService:
                    {
                        if (user.MaintenanceService == null || !user.MaintenanceService.Enabled)
                        {
                            throw new Exceptions.ServiceDisabledException();
                        }
                        return umbracoUser;
                    }
                case ServiceTypeEnum.MediaService:
                    {
                        if (user.MediaService == null
                            || !user.MediaService.Enabled
                            || !IsUserAllowedForApplication(umbracoUser, "media"))
                        {
                            throw new Exceptions.ServiceDisabledException();
                        }
                        return umbracoUser;
                    }
                case ServiceTypeEnum.PackageService:
                    {
                        if (user.PackageService == null || !user.PackageService.Enabled)
                        {
                            throw new Exceptions.ServiceDisabledException();
                        }
                        return umbracoUser;
                    }
                default:
                    return null;
            }
        }

        /// <summary>
        /// Determines whether the user is allowed for the named application.
        /// </summary>
        /// <param name="umbracoUser">The umbraco user.</param>
        /// <param name="AppAlias">The application alias.</param>
        /// <returns>
        /// 	<c>true</c> if user is allowed for the named application otherwise, <c>false</c>.
        /// </returns>
        private bool IsUserAllowedForApplication(umbraco.BusinessLogic.User umbracoUser, String appAlias)
        {
            foreach (umbraco.BusinessLogic.Application app in umbracoUser.Applications)
            {
                if (app.alias == appAlias)
                {
                    return true;
                }
            }
            return false;
        }

    }
}
